<template>
	<view class="content">
		<u-cell-group>
			<view style="height: 60px;line-height: 60px;">
				<u-cell-item title="头像" :center="true" :titleStyle="titleColor" @click="click">
					<image class="img" mode="aspectFill" :src="miniAvatar"/>
				</u-cell-item>
			</view>
			<u-cell-item title="名字" @click="changeUpdate({ title: '名字', type: 'nickname', value: _user_info.nickname })" :center="true" :value="_user_info.nickname" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="账号" @click="changeUpdate({ title: '账号',type: 'account',  value: _user_info.account })" :center="true" :value="_user_info.account" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="性别" @click="changeSex" :center="true" :value="sex" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="地区" @click="showArea = true" :center="true" :value="_user_info.area" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="个性签名" @click="changeUpdate({ title: '个性签名',type: 'signature',  value: _user_info.signature })" :center="true" :value="_user_info.signature" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="职业" @click="changeUpdate({ title: '职业',type: 'work',  value: _user_info.work })" :center="true" :value="_user_info.work" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="公司" @click="changeUpdate({ title: '公司',type: 'company',  value: _user_info.company })" :center="true" :value="_user_info.company" :titleStyle="titleColor"></u-cell-item>
			<u-cell-item title="出生日期" @click="show = true" :center="true" :value="birthday" :titleStyle="titleColor"></u-cell-item>
			<!-- <u-calendar v-model="show" :mode="mode" @change="changeDate"></u-calendar> -->
			<u-picker mode="time" v-model="show" :params="params" @confirm="changeDate"></u-picker>
			<u-picker mode="region" v-model="showArea" :default-region='["广东省", "揭阳市", "普宁市"]' @confirm="changeArea"></u-picker>
			<u-toast ref="uToast" />
		</u-cell-group>
	</view>
	
</template>

<script>
import { api } from '../../api/api';
import { myRequest } from '../../util/api';

	export default {
		data() {
			return {
				titleColor: { color: 'black', lineHeight: '36px', },
				miniAvatar: '',
				sex: 1,
				show: false,
				showArea: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				mode: 'date',
				birthday: ''
			}
		},
		onLoad() {
			this.miniAvatar = this._user_info.miniAvatar
			this.sex = this._user_info.sex  == 1 ? '男' : '女'
			this.birthday = this._user_info.birthday
		},
		methods: {
			// 选择出生日期
			async changeDate(e) {
				const year = e.year;
				const month = String(e.month).padStart(2, '0');
				const day = String(e.day).padStart(2, '0');
				const date = `${year}-${month}-${day}`;
				await this.updateUserInfo('birthday', date);
			},
			// 选择地区
			async changeArea(e) {
				// const province = e.province.label;
				const city = e.city.label;
				const area = e.area.label;
				const areaFormat = `${city} ${area}`;
				await this.updateUserInfo('area', areaFormat);
			},
			// 性别
			changeSex() {
				plus.nativeUI.actionSheet({
					cancelBtn: false,
					buttons: [
						{ title: '男' },
						{ title: '女' }
					]
				}, async (e) => {
					const sex = e.index === 1 ? 1 : 2;
					await this.updateUserInfo('sex', sex);
				});
			},
			// 更新用户信息的通用方法
			async updateUserInfo(field, value) {
				try {
					const response = await myRequest({
						url: api.updateUserInfo,
						method: 'POST',
						data: {
							field: field,
							value: value,
						},
						success:(response)=>{
							if (response.data.code === 200 && response.data.httpCode === 200) {
								this.$store.commit('$uStore', { name: `_user_info.${field}`, value: value });
								this[field] = field === 'sex' ? (value === 1 ? '男' : '女') : value;
							} else {
								this.handleUpdateFailure(response.data.message);
							}
						}
					});
				} catch (error) {
					this.handleUpdateFailure('请求失败，请稍后再试');
				}
			},
			// 处理更新失败的逻辑
			handleUpdateFailure(message) {
				uni.showToast({
					title: '信息更新失败: ' + message,
					position: "bottom"
				});
			},

			
			async click() {
				var self = this; // 将 this 绑定到 self 变量
			    var user = uni.getStorageSync('_user_info');
			    var upload_url = this.$BASE_URL + api.upload;
			
			    // 弹出选择对话框，允许用户选择相册或拍照
			    plus.nativeUI.actionSheet({
			        cancel: '取消',
			        buttons: [
			            { title: '拍照' },
			            { title: '从相册选择' }
			        ]
			    }, function(e) {
			        if (e.index === 1) {
			            // 用户选择了“拍照”
			            captureImage();
			        } else if (e.index === 2) {
			            // 用户选择了“从相册选择”
			            pickFromGallery();
			        }
			    });
			
				// 调用拍照
			    function captureImage() {
			        var cmr = plus.camera.getCamera();
			        cmr.captureImage(function(path) {
			            uploadImage(path);
			        }, function(e) {
			            console.log('取消拍照: ' + e.message);
			        }, { crop:{ width: '360px', height: '360px', quality: 100, resize: false } });
			    }
			
				// 打开相册
			    function pickFromGallery() {
			        plus.gallery.pick(function(path) {
			            uploadImage(path);
			        }, function(e) {
			            console.log('取消选择');
			        }, { filter: "image", crop: { width: '360px', height: '360px', quality: 100, resize: false } });
			    }
			    function uploadImage(path) {
			        // 1. 创建一个上传任务对象
			        var task = plus.uploader.createUpload(upload_url,
			            {},
			            function(t, status) {
			                var resp = JSON.parse(t.responseText);
			                // 上传完成
			                if (resp.code == 200 && resp.httpCode == 200) {
			                    var maxHead = resp.data.url;
			                    var minHead = resp.data.thumbnailUrl;
			                    // 更改本地用户信息存储
			                    self.$store.commit('$uStore', { name: `_user_info.miniAvatar`, value: minHead });
			                    self.$store.commit('$uStore', { name: `_user_info.avatar`, value: maxHead });
								self.miniAvatar = minHead
			                } else {
			                    plus.nativeUI.toast('上传失败');
			                }
			            }.bind(this)
			        );
			        // 2. 添加上传的文件
			        task.addFile(path, { key: "file" });
			        // 3. 设置其他参数
			        task.addData("userId", user.id + "");
			        console.log(user.id);
			        // 4. 上传
			        task.start();
			        plus.nativeUI.toast('更换成功');
			    }
			},

			// 跳转至修改页面
			changeUpdate(params) {
				if (params.type == 'nickname' || params.type == 'account' || params.type == 'work' || params.type == 'company'){
					params.title = '更改'+params.title
				} else if(params.type == 'sex') {
					params.title = '设置'+params.title
				} else if(params.type == 'area') {
					params.title = '选择'+params.title
				}
				// 带参数
				this.$u.route('pages/updateMyInfo/updateMyInfo', {
					title: params.title,
					type: params.type,
					value: params.value,
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.img {
		width: 90rpx;
		height: 90rpx;
		border-radius: 6px;
		// margin-top: 10rpx;
	}
</style>
